package cn.lijiguo.concurrency.part1.ch06;

/**
 * RightWayStopThreadInProd
 * 在实际开发中正确的方式停止线程
 * 最佳实战：catch 了 InterruptedException 的优先选择，在方法签名中抛出异常
 *  那么在 run() 方法中 就会强制 try/catch
 * @author lijiguo
 * @date 2020/1/6 11:19
 */
public class RightWayStopThreadInProd implements Runnable {

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new RightWayStopThreadInProd(), "t1");
        t1.start();

        Thread.sleep(1000);
        t1.interrupt();
    }

    @Override
    public void run() {
        while (true) {
            if(Thread.currentThread().isInterrupted()) {
                System.out.println("线程即将终止---");
                break;
            }
            System.out.println("go...");
            try {
                throwInMethod();
            } catch (InterruptedException e) {
                System.out.println("线程被打断----");
                e.printStackTrace();
            }
        }
    }

    /**
     * 使用 方法签名 抛出异常
     * @throws InterruptedException
     */
    private void throwInMethod() throws InterruptedException {
        Thread.sleep(2000);
    }
}
